#!/usr/bin/python
# -*- coding: utf8
import sys

__author__ = 'mkompan'

import copy
import json

import urllib2
import urllib
import hashlib
import hmac
import base64

_EC2_CONFIG = 'ec2_config.py'

class EC2Command(object):
    def __init__(self, **kwargs):
        self._request_dict = kwargs

    @property
    def request_dict(self):
        return self._request_dict

    @staticmethod
    def parse_json(response_string):
        res_dict = json.loads(response_string)
        return res_dict


def get_item_id(item, name, **kwargs):
    response = command(EC2Command(command='list%s' % item, **kwargs))
    for item in response_body(response):
        if item['name'] == name:
            return item['id']
    return None


def get_service_offering_id(name):
    return get_item_id('ServiceOfferings', name)


def get_template_id(name, filter='community'):
    return get_item_id('Templates', name, templatefilter=filter)


def get_zone_id(name):
    return get_item_id('Zones', name)


def get_disk_offering_id(name):
    return get_item_id('DiskOfferings', name)


def get_network_id(name):
    return get_item_id('Networks', name)


def get_security_group_id(name):
    return get_item_id('SecurityGroups', name)


class ListUsers(EC2Command):
    def __init__(self):
        self._request_dict = {'command': 'listUsers'}

    @staticmethod
    def parse_json(response_string):
        res_dict = json.loads(response_string)
        return res_dict['listusersresponse']['user']


def command(request_class,
            timeout=5):
    apikey = None
    secretkey = None
    baseurl = None
    exec (open(_EC2_CONFIG))
    request = copy.copy(request_class.request_dict)
    request['response'] = 'json'
    request['apikey'] = apikey

    request_str = '&'.join(['='.join([k, urllib.quote_plus(request[k])]) for k in request.keys()])

    request_keys = sorted(request.keys())
    #TODO: cloudstack documentation is INCORRECT (python example)!!! correct signature string generated as folows:
    sig_str = '&'.join(['='.join([k.lower(), urllib.quote_plus(request[k]).lower()]) for k in request_keys])

    sig = urllib.quote_plus(base64.encodestring(hmac.new(secretkey, sig_str, hashlib.sha1).digest()).strip())
    try:
        res = urllib2.urlopen(baseurl, request_str + '&signature=' + sig , timeout=timeout)
    except urllib2.HTTPError as e:
        print "HTTP ERROR %s\n %s" % (e.code, e.info())
        sys.exit(1)
    return request_class.parse_json(res.read())



def response_body(response):
    r1 = response[response.keys()[0]]
    for key in r1.keys():
        if key != 'count':
            break
    return r1[key]


if __name__ == "__main__":
    print command(ListUsers())